using AutoMapper;
using Microsoft.EntityFrameworkCore;
using PowerManage.EntityFrameworkCore;
using PowerManage.Entity;
using PowerManage.Entity.Dtos.Permissions;
using PowerManage.Entity.Dtos.Users;

namespace PowerManage.Service.Impl;

public class PermissionService : BaseService, IPermissionService
{
    private readonly ApplicationDbContext _dbContext;
    private readonly IMapper _mapper;

    public PermissionService(ApplicationDbContext dbContext, IMapper mapper)
    {
        _dbContext = dbContext;
        _mapper = mapper;
    }

    /// <summary>
    /// 获取所有权限
    /// </summary>
    /// <returns></returns>
    public async Task<List<PermissionDto>> GetAll()
    {
        var permissionDtos = new List<PermissionDto>();
        var permissionList = await _dbContext.ElePermission.ToListAsync();
        foreach (var permission in permissionList)
        {
            var permissionDto = _mapper.Map<PermissionDto>(permission);

            var user = _dbContext.Users.FirstOrDefault(x => x.Id == permissionDto.Id);
            permissionDto.Creator = _mapper.Map<UserDto>(user);
            permissionDtos.Add(permissionDto);
        }

        return permissionDtos;
    }

    /// <summary>
    /// 添加权限
    /// </summary>
    /// <param name="permission"></param>
    /// <returns></returns>
    public async Task<ElePermission> Add(ElePermission permission)
    {
        var count = await _dbContext.ElePermission.CountAsync(x => x.Code == permission.Code);
        if (count > 0)
        {
            return null;
        }

        await _dbContext.AddAsync(permission);
        await _dbContext.SaveChangesAsync();
        return permission;
    }

    /// <summary>
    /// 通过id获取权限
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<ElePermission?> GetById(long id)
    {
        return await _dbContext.ElePermission.FirstOrDefaultAsync(x => x.Id == id);
    }

    /// <summary>
    /// 更新权限
    /// </summary>
    /// <param name="permission"></param>
    /// <returns></returns>
    public async Task<bool> Update(ElePermission permission)
    {
        var count = await _dbContext.ElePermission.CountAsync(x => x.Code == permission.Code && x.Id != permission.Id);
        if (count > 0)
        {
            return false;
        }

        permission.LastModificationTime = DateTime.Now;
        _dbContext.Update(permission);
        await _dbContext.SaveChangesAsync();
        return true;
    }

    /// <summary>
    /// 删除权限
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<bool> Delete(long id)
    {
        var permission = await _dbContext.ElePermission.FirstOrDefaultAsync(x => x.Id == id);
        if (permission == null)
        {
            return false;
        }

        _dbContext.Remove(permission);
        await _dbContext.SaveChangesAsync();
        return true;
    }
}